<?php

class Helper_Log
{
	/**
	 * list of logger need to be execute
	 */
	protected $_vars = array();

	/**
	 * @var array
	 */
	protected $_options = array();
	
	/**
	 * constructor
	 * @return void
	 */
	public function __construct()
	{
		$this -> _options = array();
	}
	
	/**
	 * get log writter
	 * @param string name
	 * @return Log
	 */
	public function getWriter($name)
	{
		return isset($this -> _vars[$name]) ? $this -> _vars[$name] : ($this -> _vars[$name] = $this -> _create($name));
	}
	
	/**
	 * @param string $options
	 * @param any $default
	 * @return any
	 * */
	public function getOptions($name, $default = null)
	{
		return isset($this -> _options) ? $this -> _options : $default;
	}
	
	protected function _create($name)
	{
		$file = TEMP_PATH . '/log/' . $name . '.log';
		return new Log_Writer_File($file);
	}
	
	/**
	 * Error handler
	 *
	 * @param integer $errno
	 * @param string $errstr
	 * @param string $errfile
	 * @param integer $errline
	 * @param array $errcontext
	 */
	public function handleError($errno, $errstr, $errfile = null, $errline = null, array $errcontext = null)
	{
		$this -> getWriter('error') -> write($errno, $errstr, $errfile, $errline, $this -> formatBacktrace());
		return 1;
	}
	
	/**
	 * Exception handler
	 *
	 * @param Exception $exception
	 */
	public function handleException($exception)
	{
		$this -> getWriter('error') -> write($exception -> __toString(), $this -> formatBacktrace());
		return 1;
	}
	
	public function formatBacktrace()
	{
		$backtrace = array_slice(debug_backtrace(), 1);

		$output = '';
		$index = 0;

		foreach ($backtrace as $index => $stack)
		{
			// Process args
			$args = array();
			if (!empty($stack['args']))
			{
				foreach ($stack['args'] as $argIndex => $argValue)
				{
					if (is_object($argValue))
					{
						$args[$argIndex] = get_class($argValue);
					}
					else
					if (is_array($argValue))
					{
						$args[$argIndex] = 'Array';
						//substr(print_r($argValue, true), 0, 32);
					}
					else
					if (is_string($argValue))
					{
						$args[$argIndex] = "'" . substr($argValue, 0, 32) . (strlen($argValue) > 32 ? '...' : '') . "'";
					}
					else
					{
						$args[$argIndex] = print_r($argValue, true);
					}
				}
			}
			// Process message
			$output .= sprintf('#%1$d %2$s(%3$d): %4$s%5$s%6$s(%7$s)', $index, (!empty($stack['file']) ? $stack['file'] : '(unknown file)'), (!empty($stack['line']) ? $stack['line'] : '(unknown line)'), (!empty($stack['class']) ? $stack['class'] : ''), (!empty($stack['type']) ? $stack['type'] : ''), $stack['function'], join(', ', $args));
			$output .= PHP_EOL;
		}

		// Throw main in there for the hell of it
		$output .= sprintf('#%1$d {main}', $index + 1);

		return $output;
	}

}
